package com.lagou.config;

import com.lagou.com.lagou.mapping.SqlCommandType;
import com.lagou.com.lagou.mapping.SqlNodesType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }


    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        putMappedStatementMap( rootElement,  namespace,  SqlNodesType.SELECT.getName());
        putMappedStatementMap( rootElement,  namespace,  SqlNodesType.INSERT.getName());
        putMappedStatementMap( rootElement,  namespace,  SqlNodesType.UPDATE.getName());
        putMappedStatementMap( rootElement,  namespace,  SqlNodesType.DELETE.getName());
    }


    public void putMappedStatementMap(Element rootElement, String namespace, String sqlType) {
        List<Element> list = rootElement.selectNodes(sqlType);
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            //sql语句类型为 SELECT
            mappedStatement.setSqlCommandType(SqlCommandType.SELECT);
            switch (sqlType) {
                case "//select": {
                    mappedStatement.setSqlCommandType(SqlCommandType.SELECT);
                    break;
                }
                case "//update": {
                    mappedStatement.setSqlCommandType(SqlCommandType.UPDATE);
                    break;
                }
                case "//delete": {
                    mappedStatement.setSqlCommandType(SqlCommandType.DELETE);
                    break;
                }
                case "//insert": {
                    mappedStatement.setSqlCommandType(SqlCommandType.INSERT);
                    break;
                }
                default:
                    throw new IllegalStateException("Unexpected value: " + sqlType);
            }
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

}
